<script lang="ts">
import navi from "@/components/AdminNavi.vue";
import request from "@/utils/request";
import {onMounted, reactive, ref} from "vue";
import {ElMessage, FormInstance, FormRules} from "element-plus";
export default {
  components:{
    'navi':navi
  },
  setup(){
    const proUrl=ref("")
    const list=ref([])
    const addFormRef=ref<FormInstance>()
    const changeFormRef=ref<FormInstance>()
    interface RuleForm{
      proName:string
      proType:string
      proPrice:number
      proDescription:string
      proInventory:number
      other1:string
      other2:string
    }
    const addForm=reactive({
      proName:'',
      proType:'',
      proImg:'',
      proPrice:0,
      proDescription:'',
      proInventory:0,
      other1:'',
      other2:'',
    })
    const changeForm=reactive({
      proId:'',
      proName:'',
      proType:'',
      proImg:'',
      proPrice:0,
      proDescription:'',
      proInventory:0,
      other1:'',
      other2:'',
    })
    const addRules = reactive<FormRules<RuleForm>>({
      proName: [
        { required: true, message: '商品名不可为空', trigger: 'blur' }],
      proType: [
        { required: true, message: '未选择分类', trigger: 'blur' }],
      proPrice: [
        { required: true, message: '商品价格不可为空', trigger: 'blur' }],
      proDescription: [
        { required: true, message: '商品简介不可为空', trigger: 'blur' }],
      proInventory: [
        { required: true, message: '商品库存不可为空', trigger: 'blur' }],
      other1: [
        { required: true, message: '作者不可为空', trigger: 'blur' }],
      other2: [
        { required: true, message: '出版社不可为空', trigger: 'blur' }]
    });

    const total=ref('')
    const addFormVisible = ref(false)
    const changeFormVisible = ref(false)
    const formLabelWidth = '140px'
    const params = ref({
      page: 1,
      size: 4
    })

    onMounted(()=>{
      pagehelper()
    })

    const pagehelper = async() => {
      const res=await request.get(`/adminProduct/${params.value.page}/${params.value.size}`)
      console.log(res.data)
      list.value=res.data.data.records
      total.value =res.data.data.total
    }
    const handleSizeChange = (val: number) => {
      console.log(`每页 ${val} 条`)
      params.value.size = val
      pagehelper()
    }

    const handleCurrentChange = (val: number) => {
      console.log(`当前页: ${val}`)
      params.value.page = val
      pagehelper()
    }
    const value = ref('')

    function handleImgSuccess(res: { data: string; }){
      proUrl.value=res.data
      addForm.proImg=res.data
      console.log(res)
    }
    // const addProduct = async() =>{
    //   const res=await request.post('/addProduct',addForm)
    //   addFormVisible.value=false
    // }
    const addProduct = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate(async (valid, fields) => {
        if (valid) {
          console.log('submit!')
          const res=await request.post('/addProduct',addForm)
          console.log(res.data)
          addFormVisible.value=false
          ElMessage.success("添加商品成功")
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    const changeProduct = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate(async (valid, fields) => {
        if (valid) {
          console.log('submit!')
          console.log(changeForm)
          const res=await request.post(`/changeProduct`,changeForm)
          console.log(res.data)
          changeFormVisible.value=false
          ElMessage.success("修改商品成功")
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    const changeProductButton = async (row:any) => {
      const res= await request.get(`/goods/${row.proId}`)
      console.log(res.data)
      changeForm.proId = row.proId
      changeForm.proName = res.data.data.proName
      changeForm.proImg = res.data.data.proImg
      changeForm.proInventory = res.data.data.proInventory
      changeForm.proDescription = res.data.data.proDescription
      changeForm.proPrice = res.data.data.proPrice
      changeForm.proType = res.data.data.proType
      changeForm.other1 = res.data.data.other1
      changeForm.other2 = res.data.data.other2
      changeFormVisible.value=true
    }


    const options = [
      {
        value: '四大名著',
        label: '四大名著',
      },
      {
        value: '武侠',
        label: '武侠',
      },
      {
        value: '言情',
        label: '言情',
      },
      {
        value: '历史',
        label: '历史',
      },
      {
        value: '轻小说',
        label: '轻小说',
      },
      {
        value: '悬疑',
        label: '悬疑',
      },
      {
        value: '教科书',
        label: '教科书',
      },
      {
        value: '小说',
        label: '小说',
      }
    ]

    return{
      addRules,
      list,
      params,
      total,
      addForm,
      addFormRef,
      changeForm,
      changeFormRef,
      proUrl,
      handleSizeChange,
      handleCurrentChange,
      handleImgSuccess,
      addProduct,
      changeProduct,
      changeProductButton,
      addFormVisible,
      changeFormVisible,
      formLabelWidth,
      value,
      options,
    }
  }
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px"><navi/></el-aside>
      <el-main>
        <el-table :data="list" border style="width: 100%;margin-top: 50px" >
          <el-table-column prop="proImg"  width="180" label="商品图片">
            <template #default="scope">
              <img class="img" :src="scope.row.proImg" alt="商品图片" />
            </template>
          </el-table-column>
          <el-table-column label="商品名" prop="proName" width="250px"/>
          <el-table-column label="分类" prop="proType" width="100px"/>
          <el-table-column label="价格" prop="proPrice" width="80px"/>
          <el-table-column label="库存" prop="proInventory" width="100px"/>
          <el-table-column label="作者" prop="other1"/>
          <el-table-column label="出版社" prop="other2"/>
          <el-table-column label="">
            <template #default="scope">
              <el-button type="primary" @click="changeProductButton(scope.row)">修改商品信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="this.params.page"
                       :page-sizes="10"
                       :page-size="this.params.size"
                       layout=" prev, pager, next, jumper"
                       :total="this.total">
        </el-pagination>
        <el-button type="primary" class="addProduct" @click="addFormVisible=true">添加商品</el-button>
      </el-main>
    </el-container>
  </div>




  <el-dialog v-model="addFormVisible" title="添加商品">
    <div>
      <el-upload
          class="img-uploader"
          action="http://localhost:8081/uploadProImg"
          :show-file-list="false"
          :on-success="handleImgSuccess"
      >
        <img v-if="addForm.proImg" :src="addForm.proImg" class="img">
        <el-icon v-else class="avatar-uploader-icon" size="100px"><Plus /></el-icon>
      </el-upload>
    </div>
    <el-form ref="addFormRef"
             :model="addForm"
             :rules="addRules">
      <el-form-item label="商品名:" :label-width="formLabelWidth" prop="proName">
        <el-input v-model="addForm.proName" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="商品价格" :label-width="formLabelWidth" prop="proPrice">
        <el-input-number :precision="2" :step="0.1" :max="100" v-model="addForm.proPrice"/>
      </el-form-item>
      <el-form-item label="分类" :label-width="formLabelWidth" style="width: 300px;" prop="proType">
        <el-select v-model="addForm.proType" class="m-2" placeholder="Select" size="large">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="简介" :label-width="formLabelWidth" prop="proDescription">
        <el-input
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入简介"
            v-model="addForm.proDescription"/>
      </el-form-item>
      <el-form-item label="库存" :label-width="formLabelWidth" prop="proInventory">
        <el-input-number  v-model="addForm.proInventory"/>
      </el-form-item>
      <el-form-item label="作者" :label-width="formLabelWidth" prop="other1">
        <el-input v-model="addForm.other1" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="出版社" :label-width="formLabelWidth" prop="other2">
        <el-input v-model="addForm.other2" style="width: 300px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="addProduct(addFormRef)">
          添加
        </el-button>
        <el-button @click="addFormVisible = false" type="danger">取消</el-button>
      </span>
    </template>
  </el-dialog>


  <el-dialog v-model="changeFormVisible" title="修改商品">
    <div>
      <el-upload
          class="img-uploader"
          action="http://localhost:8081/uploadProImg"
          :show-file-list="false"
          :on-success="handleImgSuccess"
      >
        <img v-if="changeForm.proImg" :src="changeForm.proImg" class="img">
        <el-icon v-else class="avatar-uploader-icon" size="100px"><Plus /></el-icon>
      </el-upload>
    </div>
    <el-form ref="changeFormRef"
             :model="changeForm"
             :rules="addRules">
      <el-form-item label="商品名:" :label-width="formLabelWidth" prop="proName">
        <el-input v-model="changeForm.proName" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="商品价格" :label-width="formLabelWidth" prop="proPrice">
        <el-input-number :precision="2" :step="0.1" :max="100" v-model="changeForm.proPrice"/>
      </el-form-item>
      <el-form-item label="分类" :label-width="formLabelWidth" style="width: 300px;" prop="proType">
        <el-select v-model="changeForm.proType" class="m-2" placeholder="Select" size="large">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="简介" :label-width="formLabelWidth" prop="proDescription">
        <el-input
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入简介"
            v-model="changeForm.proDescription"/>
      </el-form-item>
      <el-form-item label="库存" :label-width="formLabelWidth" prop="proInventory">
        <el-input-number  v-model="changeForm.proInventory"/>
      </el-form-item>
      <el-form-item label="作者" :label-width="formLabelWidth" prop="other1">
        <el-input v-model="changeForm.other1" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="出版社" :label-width="formLabelWidth" prop="other2">
        <el-input v-model="changeForm.other2" style="width: 300px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="changeProduct(changeFormRef)">
          修改
        </el-button>
        <el-button @click="changeFormVisible = false" type="danger" >取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.img{
  height: 100px;
  width: 100px;
}
.page{
  position: fixed;
  bottom:50px;
}
.addProduct{
  position: fixed;
  bottom:50px;
}
.img-uploader .img {
  width: 178px;
  height: 178px;
  display: block;
}

.img-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.img-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.img-uploader-icon {
  font-size: 28px;
  color: #b9b9b9;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>